<?php
class UploadHelper {
	/**
	 *
	 * @param string $key 表单名
	 * @param string $save_folder 文件保存目录
	 * @throws Exception
	 * @return array
	 */
	public static function upload($key, $save_folder, $allow_exts=[])
	{
		try{
			if( isset($_FILES[$key]))
			{
				$files = array();
				if ( is_array( $_FILES[$key]['name'] )) {
					foreach($_FILES[$key]['name'] as $k => $filename)
					{
						//检查文件上传是否有错误
						switch ($_FILES[$key]['error'][$k]){
							case UPLOAD_ERR_INI_SIZE: //1 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
							case UPLOAD_ERR_FORM_SIZE:  //2 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
							case UPLOAD_ERR_PARTIAL:  //3 文件只有部分被上传。
							case UPLOAD_ERR_NO_TMP_DIR: //6 找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。
							case UPLOAD_ERR_CANT_WRITE: //7 文件写入失败。PHP 5.1.0 引进。
							case UPLOAD_ERR_NO_FILE:  //4 没有文件被上传。
								throw new Exception('上传失败',$_FILES[$key]['error'][$k]); //上传失败
								break;
						}
						$_tmp = explode('.', $filename);
						$ext_name = end($_tmp);
						if( count($allow_exts) &&  !in_array( strtolower($ext_name), $allow_exts)){
							throw new Exception('不允许的文件格式', 11);
						}
						$basename = time(). self::getRandChar(4);
					    $original_filename = $filename;
						$filename = $basename .".".$ext_name;
						$uploadfile = chop($save_folder,'/') . '/'. $filename;
						$destination = chop(public_path(),'/') . "/" . chop($save_folder,'/');
						if (!is_dir($destination)) {
							mkdir($destination, 0777, true);
						}
						if (move_uploaded_file($_FILES[$key]['tmp_name'][$k], $destination . '/' . $filename)) {
							$files[$k] = array(
								'path' =>	$uploadfile,
								'ext'  => $ext_name,
								'basename' => $basename,
							    'original_filename' => $original_filename
							);
						} else {
							throw new Exception('上传失败',5); //上传失败
						}
					}
				}else{
					$filename= $_FILES[$key]['name'];
					switch ($_FILES[$key]['error']){
						case UPLOAD_ERR_INI_SIZE: //1 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
						case UPLOAD_ERR_FORM_SIZE:  //2 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
						case UPLOAD_ERR_PARTIAL:  //3 文件只有部分被上传。
						case UPLOAD_ERR_NO_TMP_DIR: //6 找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。
						case UPLOAD_ERR_CANT_WRITE: //7 文件写入失败。PHP 5.1.0 引进。
						case UPLOAD_ERR_NO_FILE:  //4 没有文件被上传。
							throw new Exception('上传失败',$_FILES[$key]['error']); //上传失败
							break;
					}
					$_tmp = explode('.', $filename);
					$ext_name = end($_tmp);
					if( count($allow_exts) &&  !in_array( strtolower($ext_name), $allow_exts)){
						throw new Exception('不允许的文件格式', 11);
					}	
					$basename = time(). self::getRandChar(4);
					$original_filename = $filename;
					$filename = $basename .".".$ext_name;
					$uploadfile = chop($save_folder,'/') . '/'. $filename;
					$destination = chop(public_path(),'/') . "/" . chop($save_folder,'/');
					if (!is_dir($destination)) {
						mkdir($destination, 0777, true);
					}
					if (move_uploaded_file($_FILES[$key]['tmp_name'], $destination . '/' . $filename)) {
						$files[0] = array(
							'path' =>	$uploadfile,
							'ext'  => $ext_name,
							'basename' => $basename,
							'filename' => $basename.'.'.$ext_name,
						    'original_filename' => $original_filename
						);
					} else {
						throw new Exception('上传失败',5); //上传失败
					}
				}				
				return array('error' => 0, 'files' => $files);
			}elseif( isset($_POST[$key]) ){
				$files = array();
				foreach($_POST[$key] as $k=>$file ){
					$filename = $file['name'];
					$_tmp = explode('.', $filename);
					$ext_name = end($_tmp);
					if( count($allow_exts) &&  !in_array( strtolower($ext_name), $allow_exts)){
						throw new Exception('不允许的文件格式', 11);
					}
					$basename = time(). self::getRandChar(4);
					$uploadfile = chop($save_folder,'/') . '/'. $basename .".".$ext_name;
					file_put_contents($uploadfile, base64_decode( substr($file['data'], strpos($file['data'],',')+1 )) );					
					$files[$k] = array(
							'path' =>	$uploadfile,
							'ext'  => $ext_name,
							'basename' => $basename,
							'filename' => $basename.'.'.$ext_name
					);
				}
				return array('error' => 0, 'files' => $files);
			}else{
				return array('error' => 0, 'files' => [] );
			}
	
		}
		catch(Exception $e)
		{
			return array('error' => $e->getCode(), 'message' => $e->getMessage() );
		}
	}
	
	public static  function getRandChar($length){
		$str = null;
		$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
		$max = strlen($strPol)-1;
		for($i=0;$i<$length;$i++){
			$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
		}
	
		return $str;
	}
	
	public static function uploadImage($key, $save_folder, $crateThumb=FALSE) {
		$allow_exts = ['jpg','jpeg','jpe','png','gif','bmp'];
		if ( !is_dir($save_folder) ) {
			mkdir($save_folder, 0777,true);
		}
		$result = self::upload($key, $save_folder, $allow_exts);
		if($crateThumb) {
			foreach ($result['files'] as $index => $f){
				foreach( array(ImageHelper::SIZE_BIG, ImageHelper::SIZE_MEDIUM, ImageHelper::SIZE_SMALL) as $size ){			
					$thumbname = chop($save_folder,'/').'/'.$f['basename'] .'_' . $size .'.' .$f['ext'];
					$result['files'][$index]['thumb'] = ImageHelper::thumb($f['path'], $thumbname, $size );
				}
			}
		}
		return $result;
	}

	public static function preprocessUploadFilePath($file_path) {
		$file_path = preg_replace("/^https?\:\/\/([^\/?#]+)/i", "", $file_path);
		return $file_path;
	}

	public static function getFileFolder($path) {
		return Config::get('app.upload_root') . $path;
	}

}